$.fn.alternateRowColors = function() {
    $('tbody tr:odd', this).removeClass('even').addClass('odd');
    $('tbody tr:even', this).removeClass('odd').addClass('even');
    return this;
};
$('#tabs').tabs();

$(document).ready(function(){
    $('#submit').button().click(function(){
            $('#form_backlog').submit();});
    $('#btninstask').button();
    $('#btninspend').button();
    $('.tips').tipsy({
        title:'obs',
        gravity: $.fn.tipsy.autoWE,
        delayIn:1000,
        delayOut:500,
        html:true
    });
    $('.tipsw').tipsy({
        title:'obs',
        gravity: 'w',
        delayIn:1000,
        delayOut:500,
        html:true
    });
    $.ajaxSetup({
        cache: false,
        type: 'POST',
        dataType: 'json',
        error: function () {
            alert('Um erro de comunicação com o servidor ocorreu!');
            $('#ajax-ldr').fadeOut('fast');
        }
    });

    $('.arquivos').click(function(){
        var aux = $(this).attr('arq');
        window.open('/chamadas/arquivo/id/'+aux,'Anexo....');
        return false;
    });


    $('textarea.tinymce').tinymce({
        // Location of TinyMCE script
        script_url : '/js/tiny_mce/tiny_mce.js',

        // General options
        theme : "advanced",
        plugins: "",
        //plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

        // Theme options
        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
        theme_advanced_buttons2 : '',
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        ///content_css : "css/content.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js",

        // Replace values for the template plugin
        template_replace_values : {
            username : "Some User",
            staffid : "991234"
        }
    });
    $('#novapendencia').click(function(){
        if ($('#criapend').is(':visible')){
            $('#criapend').slideUp();
        }else{
            $('#criapend').slideDown(2000);
        }
        return false;
    });
    $('#novatarefa').click(function(){
        if ($('#criatar').is(':visible')){
            $('#criatar').slideUp();
        }else{
            $('#criatar').slideDown(2000);
        }
        return false;
    });
    $('.removerchamada').click(function(){
       var chamada = $(this).attr('cha');
       //alert(chamada); 
       var e = this;
       $.ajax({
            url: "/backlogs/rempend",
            processData: false,
            data: 'chamada_id='+chamada+'&backlog_id='+$('#id').val(),
            beforeSend: function (){
                var pos = $(e).offset();
                var width = $(e).width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                if (msg==false){
                    alert('Erro, removendo a pendência do Backlog');
                }else{
                    //$('#pendenc').append($('<li>').text($('#idpend').val()));
                    $(e).remove();
                    $('#tr_'+msg.tarefaid).remove();
                    $('#li_'+chamada).remove();
                }
                $('#ajax-ldr').fadeOut('fast');
            }
        });
        return false;
    });

    $('#btninspend').click(function(){
        $.ajax({
            url: "/backlogs/addpend",
            processData: false,
            data: 'chamada_id='+$('#idpend').val()+'&backlog_id='+$('#id').val(),
            beforeSend: function (){
                var pos = $('#btninspend').offset();
                var width = $('#btninspend').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+10) + "px",
                    "top":pos.top+2 + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                if (msg['status']==false){
                    alert('Erro, Pendencia não incluída no Backlog');
                }else{
                    //$('#pendenc').append($('<li>').text($('#idpend').val()));
                    if(msg(['status'])=='removido'){
                        
                    }else{
                        $('#pendenc').append($('<span>').attr('class','span-5').append($('<li>').text($('#idpend').val())));
                        $('#idpend').val('');
                    }
                    $('#tarefas')
                        .append($('<tr>')
                            .append($('<td>').text(msg.tarefa.pendencia_id).attr('align','center'))
                            .append($('<td>').text(msg.tarefa.nome))
                            .append($('<td>').text(' '))
                            .append($('<td>').text(msg.tarefa.priori).attr('align','center'))
                            .append($('<td>').text(msg.tarefa.estado).attr('align','center'))
                            .append($('<td>').text(' '))
                            .append($('<td>').text(' ').attr('align','center'))
                            .append($('<td>').text(' ').attr('align','center'))
                            .append($('<td>'))
                            .append($('<td>'))
                        );
                }
                $('#ajax-ldr').fadeOut('fast');
            }
        });
    });
    $('#btninstask').click(function(){
        $.ajax({
            url: "/tasks/adicionatarefa",
            processData: false,
            data: 'backlog_id='+$('#id').val()+'&sprint_id='+$('#sprint_id option:selected').val()+'&descricao='+escape($('#descricao').val())+
            '&story_point='+$('#story_point').val()+'&horas_previstas='+$('#horas_previstas').val()+
            '&estado_id='+$('#estado_id').val()+'&prioridade='+$('#prioridade_tar').val()+'&user_id='+$('#user_id').val()+'&nome='+$('#nome').val(),
            beforeSend: function (){
                $('.error').hide();
                var pos = $('#btninstask').offset();
                var width = $('#btninstask').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+10) + "px",
                    "top":pos.top+2 + "px"
                } ).fadeIn('fast');
            },
            success: function(msg){
                if (msg==true){
                    $('#tarefas')
                    .append($('<tr>')
                        .append($('<td>'))
                        .append($('<td>').text($('#nome').val()))
                        .append($('<td>').text($('#sprint_id').val()))
                        .append($('<td>').text($('#prioridade_tar option:selected').text()).attr('align','center'))
                        .append($('<td>').text($('#estado_id option:selected').text()).attr('align','center'))
                        .append($('<td>').text($('#user_id option:selected').text()))
                        .append($('<td>').text($('#story_point').val()).attr('align','center'))
                        .append($('<td>').text($('#horas_previstas').val()).attr('align','center'))
                        .append($('<td>'))
                        .append($('<td>'))
                        );
                    $('#sprint_id').val('');
                    $('#nome').val('');
                    $('#descricao').val('');
                    $('#story_point').val('');
                    $('#horas_previstas').val('');
                    $('#criatar').slideUp(800);
                    $('#ajax-ldr').fadeOut('fast');
                    $('#tarefas').alternateRowColors();
                }else{
                    alert('Erro criando tarefa!\nEsta tarefa não foi criada.');
                    $('#ajax-ldr').fadeOut('fast');
                    $('.error').hide();
                    $.each(msg,function(key,value){
                        showError(key, value);
                    });

                }
            }
        });
    });
    function showError(key,val)
    {
        var formElement = $('#'+key);
        var container = formElement.next('.error');
        if (container){
            //alert(key);
            var valor = '';
            $.each(val, function(key,value){
               valor += '<li>'+value+'</li>';
            });
            container.html('');
            container.html($('<div>')
                                .attr('class','ui-state-error ui-corner-all')
                                .html(
                                    $('<span>')
                                        .attr('class','ui-icon ui-icon-alert')
                                        .attr('style','float: left; margin-right: 0.3em;'))
                                .append(valor)
                           );
            container.show();
        }
    }
    $('#sprint_id').change(function(){
        $.ajax({
            url: "/funcionarios/index",
            processData: false,
            data: 'filtro=sprint_id&chave='+$('#sprint_id').val(),
            beforeSend: function (){
                $('#user_id option').remove();
                $('#user_id').append("<option value=''>Carregando Funcionários...</option>")
                var pos = $('#sprint_id').offset();
                var width = $('#sprint_id').width();
                $("#ajax-ldr").css( {
                    "left": (pos.left+width+5) + "px",
                    "top":pos.top + "px"
                } ).fadeIn('fast');

            },
            success: function(msg){
                $('#user_id option').remove();
                $('#user_id').append("<option value=''>Selecione o Funcionário...</option>")
                for (i = 0; i < msg.length; i++) {
                    $('#user_id').append("<option value='"+msg[i].id+"'>"+msg[i].nome+"( "+msg[i].horas+" Hrs. "+msg[i].pontos+" Pts.)"+"</option>")
                }
                $('#ajax-ldr').fadeOut('fast');
            }
        });
    });
    $('.remover').click(function(){
        var tar = $(this).attr('tar');
        if (tar!=''){
            if(confirm('Deseja realmente remover?')){
                $.ajax({
                    url: "/tasks/remover",
                    processData: false,
                    data: 'id='+tar,
                    beforeSend: function (){
                        var pos = $('#tar_'+tar).position();
                        var width = $('#tar_'+tar).width();
                        $("#ajax-ldr").css( {
                            "left": (pos.left+width+5) + "px",
                            "top":pos.top + "px"
                        } ).fadeIn('fast');

                    },
                    success: function(msg){
                        if (msg==true){
                            $('#tr_'+tar).slideUp();
                            $('#tr_'+tar).remove();
                        }else{
                            alert('A tarefa não foi removida!');
                        }
                        $('#ajax-ldr').fadeOut('fast');
                    }
                });
            }
        }
        return false;
    });
});
